<template>
    <div class="museum-creative">
        <!-- 导航栏 -->
        <div class="nav-container">
            <div class="logo">
                <span class="logo-text">文创</span>
            </div>
            <ul class="nav-menu">
                <li class="nav-item">
                    <router-link to="/museum" class="nav-link">首页</router-link>
                </li>
                <li class="nav-item">
                    <router-link to="/allproducts" class="nav-link">全部商品</router-link>
                </li>
                <li class="nav-item">
                    <router-link to="/consultation" class="nav-link">文化资讯</router-link>
                </li>
                <li class="nav-item">
                    <router-link v-if="!isLoggedIn()" to="/login" class="nav-link">登录</router-link>
                    <router-link v-if="isLoggedIn()" to="/museum" class="nav-link" @click.prevent="logout">退出</router-link>
                </li>
                <li class="nav-item">
                    <a class="nav-link cart-icon" @click.prevent="openShoppingCart">
                        <img src="@/assets/img/btn_waiter_sel.png" alt="购物车" class="cart-img">
                        <span v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="my-orders-container">
            <h2 class="page-title">我的订单</h2>

            <!-- 订单列表 -->
            <el-card class="orders-table" shadow="hover" v-loading="loading">
                <div v-if="orderList.length === 0" class="empty-orders">
                    <el-empty description="暂无订单数据"></el-empty>
                </div>
                <el-table v-else :data="orderList" border style="width: 100%" highlight-current-row>
                    <el-table-column prop="number" label="订单号" width="180" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="totalAmount" label="订单金额" width="120">
                        <template #default="scope">
                            <span>¥{{ scope.row.totalAmount.toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="paymentMethod" label="支付方式" width="100"></el-table-column>
                    <el-table-column prop="status" label="订单状态" width="100">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
                    <el-table-column label="操作" fixed="right" width="180">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
                            <el-button type="success" size="small" v-if="scope.row.status === 'shipping'"
                                @click="confirmReceipt(scope.row)">确认收货</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container" v-if="orderList.length > 0">
                    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                        :page-sizes="[5, 10, 20, 50]" v-model:current-page="queryParams.page"
                        v-model:page-size="queryParams.pageSize" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"></el-pagination>
                </div>
            </el-card>

            <!-- 订单详情对话框 -->
            <el-dialog title="订单详情" v-model="detailDialogVisible" width="800px" append-to-body>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="订单编号">{{ currentOrder.number }}</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
                    <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
                    <el-descriptions-item label="备注信息" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
                </el-descriptions>

                <div class="order-items">
                    <h3>订单商品</h3>
                    <el-table :data="currentOrder.items || []" border stripe>
                        <el-table-column prop="productName" label="商品名称"></el-table-column>
                        <el-table-column prop="productImage" label="商品图片" width="100">
                            <template #default="scope">
                                <el-image style="width: 60px; height: 60px" :src="getImageUrl(scope.row.productImage)"
                                    :preview-src-list="[getImageUrl(scope.row.productImage)]">
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="单价" width="100">
                            <template #default="scope">
                                <span>¥{{ scope.row.price.toFixed(2) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
                        <el-table-column prop="subtotal" label="小计" width="120">
                            <template #default="scope">
                                <span>¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="order-summary">
                    <div class="summary-item">
                        <span class="label">商品总价：</span>
                        <span class="value">¥{{ currentOrder.totalAmount?.toFixed(2) }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">运费：</span>
                        <span class="value">¥{{ currentOrder.shippingFee?.toFixed(2) || '0.00' }}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">优惠金额：</span>
                        <span class="value">- ¥{{ currentOrder.discount?.toFixed(2) || '0.00' }}</span>
                    </div>
                    <div class="summary-item total">
                        <span class="label">实付金额：</span>
                        <span class="value">¥{{ currentOrder.totalAmount?.toFixed(2) }}</span>
                    </div>
                </div>

                <div class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                    <el-button type="success" v-if="currentOrder.status === 'shipping'"
                        @click="confirmReceipt(currentOrder)">确认收货</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/assets/js/api';
import { useRouter } from 'vue-router';

const router = useRouter();

// 获取当前登录用户信息
const userInfo = JSON.parse(localStorage.getItem('userId') || '{}');
const userId = userInfo;

// 查询参数
const queryParams = reactive({
    page: 1, // 当前页码
    pageSize: 5, // 每页条数
    userId: userId, // 用户ID
});

// 订单列表数据
const orderList = ref([]); // 订单列表
const total = ref(0); // 总记录数
const loading = ref(false); // 加载状态
const detailDialogVisible = ref(false); // 详情对话框可见性
const currentOrder = ref({}); // 当前选中的订单

// 购物车数量
const cartItemCount = ref(0);

// 获取订单列表数据
const getOrderList = async () => {
    if (!userId) {
        ElMessage.warning('请先登录');
        return;
    }

    loading.value = true;
    try {
        // 构建查询参数
        const params = {
            page: queryParams.page,
            pageSize: queryParams.pageSize,

            userName: userId.toString()
        };

        const response = await api.getAllOrders(params);
        orderList.value = response.data.records || [];
        total.value = response.data.total || 0;
    } catch (error) {
        ElMessage.error('获取订单列表失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

// 每页条数变化
const handleSizeChange = (size) => {
    queryParams.pageSize = size;
    getOrderList();
};

// 页码变化
const handleCurrentChange = (page) => {
    queryParams.page = page;
    getOrderList();
};

// 查看订单详情
const viewOrderDetail = async (row) => {
    try {
        loading.value = true;
        const response = await api.getOrderById(row.number);
        currentOrder.value = response.data || {};
        detailDialogVisible.value = true;
    } catch (error) {
        ElMessage.error('获取订单详情失败');
    } finally {
        loading.value = false;
    }
};

// 确认收货
const confirmReceipt = (row) => {
    ElMessageBox.confirm(`确定要确认收到订单 ${row.number} 的商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            await api.updateOrderStatus(row.number, 'completed');
            ElMessage.success('确认收货成功');

            // 获取更新后的订单详情
            const response = await api.getOrderById(row.number);
            const updatedOrder = response.data;

            // 更新列表中的订单数据
            const index = orderList.value.findIndex(o => o.number === updatedOrder.number);
            if (index !== -1) {
                orderList.value.splice(index, 1, updatedOrder);
            }

            // 如果详情对话框是为这个订单打开的，也更新它
            if (detailDialogVisible.value && currentOrder.value.number === updatedOrder.number) {
                currentOrder.value = updatedOrder;
            }

            // 如果确认收货是在详情对话框中点击的，关闭对话框
            if (detailDialogVisible.value && currentOrder.value.number === row.number) {
                detailDialogVisible.value = false;
            }

            // 刷新列表以确保数据一致性
            getOrderList();
        } catch (error) {
            ElMessage.error('确认收货失败');
            console.error('确认收货失败:', error);
        }
    }).catch(() => { });
};


function getImageUrl(imagePath) {
    return `http://localhost:8080${imagePath}`;
}

// 获取订单状态对应的类型
const getStatusType = (status) => {
    const statusMap = {
        'unpaid': 'warning',     // 待付款
        'paid': 'success',       // 已付款
        'pending': 'info',       // 待发货
        'shipping': 'primary',   // 配送中
        'completed': 'success',  // 已完成
        'cancelled': 'danger',   // 已取消
    };
    return statusMap[status] || 'info';
};

// 获取订单状态对应的文本
const getStatusText = (status) => {
    const statusMap = {
        'unpaid': '待付款',
        'paid': '已付款',
        'pending': '待发货',
        'shipping': '配送中',
        'completed': '已完成',
        'cancelled': '已取消',
    };
    return statusMap[status] || '未知状态';
};

// 检查用户是否已登录
const isLoggedIn = () => {
    return localStorage.getItem('userId') !== null;
};

// 退出登录
const logout = () => {
    localStorage.removeItem('userId');
    ElMessage.success('退出登录成功');
    router.push('/museum');
};

// 打开购物车
const openShoppingCart = () => {
    router.push('/cart');
};

// 获取购物车数量
const getCartItemCount = () => {
    const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
    cartItemCount.value = cartItems.length;
};

// 页面加载时获取订单列表和购物车数量
onMounted(() => {
    getOrderList();
    getCartItemCount();
});
</script>

<style>
@import "@/assets/css/MyOrders.css";
@import "@/assets/css/museum-product.css";
</style>
